import pao = require('../../public');
import paoClient = require('../client');
import paoControls = require('../controls');

/**
 * 导航条布局主菜单
 */
@pao.addon("导航条布局主菜单", "用导航条作为菜单的主窗体，本视图支持各种导航条，支持页面切换，页面动态加载", "pao.client")
@paoClient.template("pao/client/mainForm/navbarMainForm.html", "pao/client/mainForm/navbarMainForm.css")
export class navbarMainForm extends paoClient.baseMainForm {
    static readonly html_menu = '<li role="presentation"><a role="menuitem" tabindex="-1" name="menuItem">{0}</a></li>';
    /**
     * 导航信息
     */
    navPages?: paoControls.tabPage[];
    /**
     * 标题
     */
    $title?: JQuery = undefined;
    /**
     * 导航条
     */
    $navBar?: JQuery = undefined;
    /**
     * 内容框
     */
    $content?: JQuery = undefined;
    /**
     * 主菜单列表
     */
    $mainMenuList? : JQuery = undefined;
    /**
     * 主菜单
     */
    $mainMenu? : JQuery = undefined;
    
    /**
     * 更改页面
     * @param page 页面
     */
    changePage? (page: paoControls.tabPage) {
        let view : paoClient.baseView = pao.getObject(page.view);
        this.$title.html(page.title);

        this.navigate(view);
    }

    /**
     * 绑定事件
     */
    onAfterBind? () {
        // 渲染导航页面
        if(this.navPages) {
            for(let nav of this.navPages) {
                nav.onChangeView = (page: paoControls.tabPage) =>{
                    this.changePage(page);
                };
                nav.appendTo(this.$navBar);
            }
        }

        // 加载首页
        if (this.navPages && this.navPages[0]) {
            this.changePage(this.navPages[0]);
        }
    }
        
    /**
     * 导航到视图，如果视图是string类型，表示url，如果是baseView，表示直接导航到对象
     */
    navigate?(view: string | paoClient.baseView, caption?: string) : void{
        let targetView : paoClient.baseView = this.getView(view, caption);

        if(!targetView) 
            throw new Error(`加载视图${view}失败`);

        this.$title.html(targetView.caption);

        this.$content.children().hide();
        if(targetView.element) {
            $(targetView.element).show();
        } else {
            targetView.appendTo(this.$content[0]);
        }

        /**
         * 加载菜单
         */
        this.$mainMenuList.empty();
        if(targetView.menus && targetView.menus.length>0) {
            for(let menu of targetView.menus) {
                let menuHtml = pao.format(navbarMainForm.html_menu, menu.caption);
                let menuItem = paoClient.appendTo(this.$mainMenuList, menuHtml);

                if(menu.onClick) {
                    $(menuItem.element).find(`[name='menuItem']`).click(()=>{
                        menu.onClick();
                    });
                }
            }
            this.$mainMenu.show();
        } else {
            this.$mainMenu.hide();
        }
    }
}